<script setup lang="ts" name="CkRoot">
import { useDrop } from 'vue3-dnd'
import { storeToRefs } from 'pinia'
import { useLayoutStore } from '@/store/bigScreen/layoutStore'
import { cloneDeep } from 'lodash-es'

const layoutStore = useLayoutStore()

const { dropTo, layout } = storeToRefs(layoutStore)

const delta = ref({ x: 0, y: 0 })

const [, drop] = useDrop({
  accept: ['aside', 'tab', 'toolbar', 'package', 'item'],
  hover: (item: any, monitor) => {
    delta.value = monitor.getSourceClientOffset()
  },
  drop(item) {
    if (dropTo.value === 'root') {
      console.log(item, 'root-drop')
      const res = cloneDeep(item)
      res.options.attr.x = delta.value.x
      res.options.attr.y = delta.value.y - 25
      if (res.config.dragType === 'toolbar' && res.config.position === 'wrapper') {
        res.options.attr.y -= 42
      }
      if (res.config.dragType === 'package' && res.config.position !== 'root') {
        res.options.attr.y -= 7
      }
      if ((res.config.dragType === 'package' || res.config.dragType === 'tab' || res.config.dragType === 'item' || res.config.dragType === 'aside') && res.config.position === 'root') {
        res.options.attr.y += 2
      }
      layoutStore.moveLayout(res)
      return undefined
    }
  }
})
</script>

<template>
  <div :ref="drop" class="dnd-container root">
    <slot />
    <template v-if="layout.root.length > 0">
      <template v-for="item,index in layout.root" :key="index">
        <template v-if="item.component && item.visible">
          <component :is="item.component" :info="item" :index="index" :style="{ left: item.options.attr.x + 'px', top: item.options.attr.y + 'px', zIndex: item.options.attr.zIndex }"></component>
        </template>
      </template>
    </template>
  </div>
</template>

<style scoped lang="scss">
.dnd-container{
  position: relative;
  display: flex;
  flex: 1;
  padding: 2px;

  .root{
    position: absolute;
  }
}
</style>
